<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Gestion des fournisseurs
 * Méthode CRUD (Create, Read, Update, Delete)
 */
class Stock extends CI_Controller {

    /**
     * Constructeur de la classe
     * Appel de la librairie
     */
    function __construct() {
        parent::__construct();
        $this->load->model('matiere_premiere_model');
        $this->load->model('stock_model');
    }

    /*
      function index() {
      $matiere_premieres = $this->matiere_premiere_model->getList();
      foreach ($matiere_premieres as $matiere_premiere) {
      $matiere_premiere->STOCK = $this->stock_model->get($matiere_premiere->ARTICLE_ID)->STOCK;
      $matiere_premiere->UNITE_CODE = $this->unite_model->get($matiere_premiere->UNITE_ID)->UNITE_CODE;
      }
      $data = array(
      'matiere_premieres' => $matiere_premieres
      );

      $this->layout
      ->title('Matières premières')
      ->js('functions')
      ->js('controllers/matiere_premiere')
      ->view('matiere_premiere/index', $data);
      } */

    public function table() {


        $matiere_premieres = $this->matiere_premiere_model->getList();
        foreach ($matiere_premieres as $matiere_premiere) {
            $matiere_premiere->STOCK = $this->stock_model->get($matiere_premiere->ARTICLE_ID)->STOCK;
            $matiere_premiere->UNITE_CODE = $this->unite_model->get($matiere_premiere->UNITE_ID)->UNITE_CODE;
        }
        return json_encode($matiere_premieres);
    }

    /*     * *************************************************************************
     * EDIT
     * ************************************************************************ */

    // Create
    public function ajout() {
        $data['unites'] = $this->unite_model->getList();
        $this->load->view('stock/edit', $data);
    }

    public function ajoutDB() {
        $ARTICLE_REF = $this->input->get('ARTICLE_REF');
        $ARTICLE_LIBELLE = $this->input->get('ARTICLE_LIBELLE');
        $ARTICLE_SEUIL = $this->input->get('ARTICLE_SEUIL');
        $UNITE_ID = $this->input->get('UNITE_ID');
        $result = $this->matiere_premiere_model->create($ARTICLE_REF, $ARTICLE_LIBELLE, $ARTICLE_SEUIL, $UNITE_ID);
        echo $this->table();
    }

    /*
      // Update
      public function update() {
      $ARTICLE_ID = $this->input->get('ARTICLE_ID');
      $UNITE_ID = $this->unite_model->getList();
      $matiere_premieres = $this->matiere_premiere_model->get($ARTICLE_ID);

      $data = array(
      'matiere_premiere' => $matiere_premieres,
      'unites'=>$UNITE_ID
      );

      $this->load->view('matiere_premiere/edit', $data);
      }

      public function updateDB() {
      $ARTICLE_ID=$this->input->get('ARTICLE_ID');
      $ARTICLE_REF = $this->input->get('ARTICLE_REF');
      $ARTICLE_LIBELLE = $this->input->get('ARTICLE_LIBELLE');
      $ARTICLE_SEUIL = $this->input->get('ARTICLE_SEUIL');
      $UNITE_ID = $this->input->get('UNITE_ID');
      $result = $this->matiere_premiere_model->update($ARTICLE_ID, $ARTICLE_REF, $ARTICLE_LIBELLE, $ARTICLE_SEUIL, $UNITE_ID);
      echo $this->table();
      }

      public function Delete() {
      $ARTICLE_ID = $this->input->get('ARTICLE_ID');
      $result = $this->matiere_premiere_model->delete($ARTICLE_ID);
      echo $this->table();
      } */

    public function addstock($idArticle) {
        if ($this->input->post('addStock') == null) {
            $emplacements = $this->db
                    ->select(array('EMPLACEMENT_ID', 'EMPLACEMENT_LIBELLE'))
                    ->from('EMPLACEMENT')
                    ->get()
                    ->result()
            ;

            $data['article_id'] = $idArticle;
            $data['emplacements'] = $emplacements;

            echo $this->load->view('matiere_premiere/addStock', $data, true);
        } else {
            $empl = $this->input->post('emplacement');
            $qte = $this->input->post('quantite');

            $date = new DateTime('now', new DateTimeZone('Europe/Paris'));
            $now = $date->format('Y-m-d H:i:s');

            $data = array(
                'ARTICLE_ID' => $idArticle,
                'EMPLACEMENT_ID' => $empl,
                'STOCK_QUANTITE' => $qte,
                'STOCK_DATEENTREE' => $now,
            );

            $this->db->insert('STOCK', $data);
        }
    }

    public function removestock($idArticle) {
        $quantity = (int) $this->input->post('quantity');

        $stock = $this->db
                ->select(array('STOCK_ID', 'STOCK_QUANTITE', 'STOCK_DATEENTREE'))
                ->from('STOCK')
                ->where('ARTICLE_ID', $idArticle)
                ->order_by('STOCK_DATEENTREE', 'ASC')
                ->get()
                ->result()
        ;

        foreach ($stock as $st) {
            if ($quantity != 0) {
                if ($st->STOCK_QUANTITE > $quantity) {
                    $this->db
                            ->where('STOCK_ID', $st->STOCK_ID)
                            ->update('STOCK', array('STOCK_QUANTITE' => $st->STOCK_QUANTITE - $quantity))
                    ;
                    $quantity = 0;
                } else {
                    $this->db
                            ->where('STOCK_ID', $st->STOCK_ID)
                            ->delete('STOCK')
                    ;
                    $quantity = $quantity - (int) $st->STOCK_QUANTITE;
                }
            }
        }

        $this->checkSeuil($idArticle);
    }

    public function checkSeuil($idArticle) {
        $articles = $this->db
                ->select('ARTICLE_ID, ARTICLE_REF, ARTICLE_LIBELLE, ARTICLE_SEUIL')
                ->from('ARTICLE')
                ->where('ARTICLE_ID', $idArticle)
                ->get()
                ->result()
        ;

        foreach ($articles as $key => $art) {
            $articles[$key]->ARTICLE_SEUIL = (int) $articles[$key]->ARTICLE_SEUIL;
            $stock = $this->db
                    ->select('SUM(STOCK_QUANTITE) as STOCK')
                    ->from('STOCK')
                    ->where('ARTICLE_ID', $art->ARTICLE_ID)
                    ->get()
                    ->result();
            if (count($stock) > 0) {
                if ($stock[0]->STOCK == null)
                    $articles[$key]->STOCK = 0;
                else
                    $articles[$key]->STOCK = (int) $stock[0]->STOCK;
            }
            else
                $articles[$key]->STOCK = 0;

            if ($articles[$key]->STOCK >= $articles[$key]->ARTICLE_SEUIL)
                unset($articles[$key]);
        }

        foreach ($articles as $art) {
            if ((int) $art->STOCK < (int) $art->ARTICLE_SEUIL) {
                $this->load->library('email');

                $config['protocol'] = 'smtp';
                $config['smtp_host'] = 'smtp.bbox.fr';
                $config['smtp_port'] = 25;
                $config['mailtype'] = 'html';

                $this->email->initialize($config);

                $this->email->from('david.coquatrix@gmail.com', 'Alert Stock Plast Prod');
                $this->email->to('david.coquatrix@gmail.com');

                $this->email->subject('Alerte Stock');
                $this->email->message('<html><body><b>Le stock de l\'article suivant est bas : </b><br /><br />
                    -Reference : ' . $art->ARTICLE_REF . '<br />
                    -Libelle : ' . $art->ARTICLE_LIBELLE . '<br />
                    -Stock Actuel : ' . $art->STOCK . '<br />
                    -Stock Minimal : ' . $art->ARTICLE_SEUIL . '<br />
                    </body></html>');

                $this->email->send();

                echo $this->email->print_debugger();
            }
        }
    }

}